package com.ali.pogo;

import com.ali.sqlSession.SqlSession;

import java.util.HashMap;
import java.util.Map;

public class MapperRegistry {
    private Configuration configuration;
    private Map<Class<?>, MapperProxyFactory<?>> knowMappers = new HashMap();

    public MapperRegistry(Configuration configuration) {
        this.configuration = configuration;
    }

    public <T> T getMapper(Class<?> type, SqlSession sqlSession) throws Exception {
        MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory<T>) this.knowMappers.get(type);
        if (mapperProxyFactory == null) {
            throw new Exception(type + "is not register");
        } else {
            return mapperProxyFactory.newInstance(sqlSession);
        }
    }

    public <T> boolean hasMapper(Class<T> type) {
        return this.knowMappers.containsKey(type);
    }

    public <T> void addMapper(Class<T> type) throws Exception {
        if (type.isInterface()) {
            if (hasMapper(type)) {
                throw new Exception(type + "is register");
            }
            boolean isComplete = false;
            try {
                this.knowMappers.put(type, new MapperProxyFactory(type));
                isComplete = true;
            } catch (Exception e) {

            } finally {
                if (!isComplete) {
                    this.knowMappers.remove(type);
                }
            }
        }
    }
}
